package com.mty.system.service.impl;

import com.mty.common.entity.AclPermission;
import com.mty.common.util.JWTUtil;
import com.mty.common.vo.Result;
import com.mty.security.utils.WebUtils;
import com.mty.system.dao.AclPermissionDao;
import com.mty.system.service.AclPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher马（2508531326@qq.com）
 * @date ：Created in 2022/12/2 11:34
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class AclPermissionServiceImpl implements AclPermissionService {

    @Autowired
    private AclPermissionDao permissionDao;
    @Override
    public Result findByUserId(Long userid) {
        List<AclPermission> aclPermissions = permissionDao.selectByUserid(userid);
        return new Result<List<AclPermission>>(2000,"查询成功",aclPermissions);
    }

    @Override
    public Result<List<AclPermission>> findByUsername() {
        //1.得到当前用户的名称
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> map = JWTUtil.getTokenChaim(token);
        String username = (String) map.get("username");
        //2.调用dao中根据用户名查询该用户具有的菜单。
        List<AclPermission> aclPermissions = permissionDao.selectByUsername(username);

        //查询一级菜单
        List<AclPermission> first=new ArrayList<>();
        for (AclPermission permission : aclPermissions) {
            if (permission.getPid()==1){
              first.add(permission);
            }
        }
        for (AclPermission f : first) {
            f.setChildren(findChildren(aclPermissions,f.getId()));
        }
        return new Result<>(200,"成功",first);
    }
    public  List<AclPermission> findChildren(List<AclPermission> permissions, Long id){
            List<AclPermission> seconds=new ArrayList<>();
        for (AclPermission permission : permissions) {
            if (permission.getPid().equals(id)){
                seconds.add(permission);
            }
        }
        for (AclPermission second : seconds) {
            second.setChildren(findChildren(permissions,second.getId()));
        }
        return seconds;
    }
}
